//
//  ServeProjectViewController.m
//  Cheirapsis
//
//  Created by 田宇 on 15/11/3.
//  Copyright © 2015年 mohe. All rights reserved.
//

#import "ServeProjectViewController.h"
#import "OrderViewController.h"
#import "Define.h"
#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>
#import "iToast.h"
#import "Request.h"

@interface ServeProjectViewController ()<UIAlertViewDelegate>

@end

@implementation ServeProjectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"服务项目";
    // Do any additional setup after loading the view from its nib.
    
    _dateSource = @[
                    @{
                        @"list":@[
                                ]
                        },
                    @{
                        @"list":@[
                             @{
                                 @"title":@"联系人："
                                  },
                             @{
                                 @"title":@"手    机："
                                 },
                             @{
                                 @"title":@"备    注："
                                 }
                              ]
                        },
                    @{
                        @"list":@[
                                @{
                                    @"title":@"优惠券：",@"iamge":@"优惠券",@"jiantou":@"进入"
                                    }
                                ]
                        },
                    @{
                        @"list":@[
                                @{
                                    @"title":@"账户余额支付",@"iamge":@"余额"
                                    },
                                @{
                                    @"title":@"账户余额：",@"jiantou":@"选中"
                                    }
                                ]
                        },
                    @{
                        @"list":@[
                                @{
                                    @"title":@"支付方式：",@"iamge":@"支付方式"
                                    },
                                @{
                                    @"title":@"微信支付",@"iamge":@"微信"
                                    },
                                @{
                                    @"title":@"支付宝支付",@"iamge":@"支付宝"
                                    },
                                @{
                                    @"title":@"银行卡支付",@"iamge":@"银行卡"
                                    }
                                ]
                        }
                    ];
    
    self.tableView.scrollEnabled =NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"tableViewCell"];
    NSDictionary *dic = [_dateSource objectAtIndex:indexPath.section];
    NSArray *dicA = dic[@"list"];
    NSDictionary *smalldic = [dicA objectAtIndex:indexPath.row];
     cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(50, 5*F_HEIGHT, 60*F_WIDTH, 20*F_HEIGHT)];
//    titleLab.font = [UIFont systemFontOfSize:15.0f];
    NSString *str = smalldic [@"title"];
    CGSize size = [str sizeWithFont:titleLab.font constrainedToSize:CGSizeMake(MAXFLOAT, titleLab.frame.size.height)];
    [titleLab setFrame:CGRectMake(50, 5*F_HEIGHT, size.width, 20*F_HEIGHT)];
    titleLab.text = str;
    if (indexPath.section==1) {
        titleLab.font = [UIFont systemFontOfSize:15];
         titleLab.textColor = [UIColor lightGrayColor];
        [titleLab setFrame:CGRectMake(50, 5*F_HEIGHT, size.width, 15*F_HEIGHT)];
        [cell addSubview:titleLab];
    }
    if (indexPath.section==2) {
        titleLab.font = [UIFont systemFontOfSize:17];
        [titleLab setFrame:CGRectMake(50, 5*F_HEIGHT, size.width, 20*F_HEIGHT)];
        [cell addSubview:titleLab];
    }
    if (indexPath.section==3&&indexPath.row==1) {
        titleLab.font = [UIFont systemFontOfSize:15];
        titleLab.textColor = [UIColor lightGrayColor];
        [cell addSubview:titleLab];
    }
    if (indexPath.section==4&&indexPath.row!=0) {
        titleLab.textColor = [UIColor lightGrayColor];
        [cell addSubview:titleLab];
        
    }
    [cell addSubview:titleLab];
    UILabel *xianshi = [[UILabel alloc]initWithFrame:CGRectMake(50+size.width, 0,WIDTH-65-size.width, 25*F_HEIGHT)];
    xianshi.textAlignment = 0;
    if (indexPath.section==1&&indexPath.row==0) {
        xianshi.text = _nameString;
        [cell addSubview:xianshi];
    }
    if (indexPath.section==1&&indexPath.row==1) {
        xianshi.text = _phoneNumberString;
        [cell addSubview:xianshi];
    }
    if (indexPath.section==1&&indexPath.row==2) {
        xianshi.text = _remarksString;
        [cell addSubview:xianshi];
    }
    if (indexPath.section==2&&indexPath.row==0) {
        xianshi.text = @"0张优惠券可用";
        xianshi.textColor = [UIColor redColor];
        [xianshi setFrame:CGRectMake(50+size.width, 5*F_HEIGHT, WIDTH-65-size.width, 20*F_HEIGHT)];
        [cell addSubview:xianshi];
    }
    if (indexPath.section==3&&indexPath.row==1) {
        xianshi.text = @"0元";
        [xianshi setFrame:CGRectMake(50+size.width, 5*F_HEIGHT, WIDTH-65-size.width, 20*F_HEIGHT)];
        xianshi.font = [UIFont systemFontOfSize:15];
        [cell addSubview:xianshi];
    }
    if (indexPath.section==4) {
        [xianshi setFrame:CGRectMake(15, 29*F_HEIGHT, WIDTH-30, 1*F_HEIGHT)];
        xianshi.backgroundColor = [UIColor lightGrayColor];
        if (indexPath.section==4&&indexPath.row==3) {
            xianshi.hidden = YES;
        }
       [cell addSubview:xianshi];
    }
    
    
    UIImageView *jianTouImage = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH-20-20*F_WIDTH, 5*F_HEIGHT, 28*F_WIDTH, 20*F_HEIGHT)];
    if (indexPath.section==2&&indexPath.row==0) {
        jianTouImage.image=[UIImage imageNamed:smalldic[@"jiantou"]];
        [cell addSubview:jianTouImage];
    }
    if (indexPath.section==4&&indexPath.row==1) {
        jianTouImage.image=[UIImage imageNamed:@"选中"];
        [cell addSubview:jianTouImage];
    }
    if (indexPath.section==4&&indexPath.row==2) {
        jianTouImage.image=[UIImage imageNamed:@"选中"];
        [cell addSubview:jianTouImage];
    }
    if (indexPath.section==4&&indexPath.row==3) {
        jianTouImage.image=[UIImage imageNamed:@"选中"];
        [cell addSubview:jianTouImage];
    }
    if (indexPath.section==3&&indexPath.row==1) {
        jianTouImage.image=[UIImage imageNamed:@"选中"];
        [cell addSubview:jianTouImage];
    }
    UIImageView *titleImage = [[UIImageView alloc]initWithFrame:CGRectMake(15, 5*F_HEIGHT, 25*F_WIDTH, 20*F_HEIGHT)];
    titleImage.image = [UIImage imageNamed:smalldic[@"iamge"]];
    [cell addSubview:titleImage];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==1) {
        return 25*F_HEIGHT;
    }
    return 30*F_HEIGHT;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary *dic = [_dateSource objectAtIndex:section];
    NSArray *dicA = dic[@"list"];
    return dicA.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dateSource.count;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 80*F_HEIGHT)];
    headerView.backgroundColor = [UIColor whiteColor];
    if (section==0) {
        UIImageView *headerImage = [[UIImageView alloc]initWithFrame:CGRectMake(30, 10*F_HEIGHT, WIDTH-60, 60*F_HEIGHT)];
        headerImage.image = [UIImage imageNamed:@"提交"];
        [headerView addSubview:headerImage];
    }else {
    UILabel *headerLab = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, WIDTH-30, 15*F_HEIGHT)];
        headerLab.backgroundColor = ALL233COROL;
        headerView.backgroundColor = [UIColor whiteColor];
        headerLab.layer.cornerRadius = 2;
        headerLab.layer.masksToBounds = YES;
    [headerView addSubview:headerLab];
    }
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return 80*F_HEIGHT;
    }
    return 15*F_HEIGHT;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 70*F_HEIGHT)];
    footerView.backgroundColor = ALL233COROL;
    if (section==4) {
    UILabel *heJiLab = [[UILabel alloc]initWithFrame:CGRectMake(15, 20*F_HEIGHT, 45, 20*F_HEIGHT)];
    heJiLab.text=@"合计：";
    heJiLab.font = [UIFont systemFontOfSize:15.0f];
    [footerView addSubview:heJiLab];
    
    UILabel *moneyLab = [[UILabel alloc]initWithFrame:CGRectMake(65, 15*F_HEIGHT, 100*F_WIDTH, 30*F_HEIGHT)];
    moneyLab.textColor = [UIColor redColor];
    moneyLab.text = @"521元";
    moneyLab.font = [UIFont systemFontOfSize:30.0f];
    [footerView addSubview:moneyLab];
    
    UIButton *tijiaoBtn = [[UIButton alloc]initWithFrame:CGRectMake(100*F_WIDTH+65, 10*F_HEIGHT, 145*F_WIDTH, 40*F_HEIGHT)];
    [tijiaoBtn setTitle:@"提交订单" forState:UIControlStateNormal];
    tijiaoBtn.titleLabel.font = [UIFont systemFontOfSize:20.0f];
    tijiaoBtn.layer.cornerRadius = 5.0f;
    tijiaoBtn.backgroundColor =  [UIColor colorWithRed:159/255.0f green:203/255.0f blue:239/255.0f alpha:1];
    tijiaoBtn.layer.masksToBounds = YES;
    [tijiaoBtn addTarget:self action:@selector(Continue) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:tijiaoBtn];
    }
    
    return footerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section==4) {
       return 60*F_HEIGHT;
    }
    return 0.1;
}

-(void)Continue{
    NSMutableDictionary *orderDic = [[NSMutableDictionary alloc] init];
    if (_remarksString.length == 0) {
        [orderDic setValue:@"无" forKey:@"renarks"];
    }else {
        [orderDic setValue:_remarksString forKey:@"renarks"];
    }
    [orderDic setValue:@(200) forKey:@"money"];
    [orderDic setValue:_nameString forKey:@"contacts"];
    [orderDic setValue:[[NSUserDefaults standardUserDefaults] valueForKey:@"userName"] forKey:@"username"];
    [orderDic setValue:_phoneNumberString forKey:@"phone"];
    [orderDic setValue:_dic[@"storeAddress"] forKey:@"address"];
    [orderDic setValue:_dic[@"storeServiceType"][_k] forKey:@"type"];
    [orderDic setValue:_dic[@"storeName"] forKey:@"storeName"];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:_dateString];
    [orderDic setValue:date forKey:@"time"];
    [orderDic setValue:_dic[@"storeTel"] forKey:@"storeTel"];
    
    [[Request sharedInstance] issueOrder:orderDic];
    
    
    NSLog(@"diandiandian");
    //partner和seller获取失败,提示
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }

    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = [self generateTradeNO]; //订单ID（由商家自行制定）
    
    order.productName = @"爱邮明信片"; //商品标题
    order.productDescription = @"爱邮明信片"; //商品描述
    order.amount = [NSString stringWithFormat:@"%.2f",0.1]; //商品价格
    
    order.notifyURL =  @"http://121.42.157.121:8095/shop/action/order_pay.htm"; //回调URL
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"Cheirapsis";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    NSLog(@"orderSpec = %@",orderSpec);
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSString *resultStatus=[resultDic valueForKey:@"resultStatus"];
            if ([resultStatus isEqualToString:@"9000"]) {
                
                [self paySucceedAction];
            }
            else
            {
                [[iToast makeText:[resultDic valueForKey:@"memo"]] show];
            }
            NSLog(@"reslut = %@",resultDic);
            
        }];
        
    }
    
    
}
- (void)paySucceedAction
{
    //    NSMutableDictionary *dic1 = [[NSMutableDictionary alloc] init];
    //    [dic1 setObject:_orderId forKey:@"order_id"];
    //    [[SetRequest sharedInstance] postRequestWithURL:URL(orderPay) postParems:dic1 content:^(NetWorkModel *model) {
    //
    //        [self.navigationController popToRootViewControllerAnimated:YES];
    //
    //    }];
}

- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand(time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}
#pragma mark alipay

NSString *partner = @"2088911959654328";
NSString *seller = @"liuyi@mohekeji.com";
NSString *privateKey = @"MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANPb8Kd5UQAtsRq4f4wMY4sdw2jWwlPBUl8p7H+osDPxScDZBhzDz5Y+wuUMgoI4QwMQMBbWn8I/4028DSBskYfsXgK7+M5gEjRktXvKche/tjqifLBSIIHqLlR1NCjxr87+sFmwrtqZTZXlhByJtqbmA84gdYea26YKF3AS6z2RAgMBAAECgYBR+vnU1I0TlJrDzEEO4HxkiM/k8bWg014clQx/GbeVYfk4NsK2vs7FROQF3iFiYoML3Ge/bq3DbRV4LxylP13QltUrUxh2yxUOaZ+TCtGWEdD6aIh/iH6SC1tReliz8kioHMA/WTEUlTTzCpBOjBvHXHtstbm7yVazFO1UL29/AQJBAOxF6b48myBWhTuFXKrLl8Db0RUk7ctuz3SXwj2CQ7OHzP5wKhD6B4QtM3B4tpIlJSU7iLAkEf07/wupvwwc540CQQDljDRdeY53+2LwhE3bmy9dl0KxVMVsYu7tS/vKaJXUE2P8Sj1B3L2y/by/oVpfzWTCNTNWaS/PgaWVmgQT2fsVAkBkXHYjRp8mJ1pEpCtuqTh2xWiUsLEJnrIkdmodsn2Lfv3GfmJ//5S9wm19MulqPrj+jcFMAKZbiOaXT61FOenpAkBeaWMkSxnA2YFhIVmQiGxb1xnUK+SjZrGUohrmrktplawbGUHGtA7F7rzSKIAuRSE7C3yY/txuQYmkVVt1+sLdAkEAtay+z6UiwSzJypbCFLaqz+Eb8fwVVTCr/0jVQ9IBSlvJPFiMDZd5k/7ByHZ2X81PGm1zg1T5XMedaEHM1KWdyw==";


@end
